package com.morgan.basemodule.activity

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.morgan.basemodule.utils.GsonTypeToken
import com.morgan.basemodule.view.IBaseView
import com.morgan.basemodule.viewmodel.BaseVM

/**
 *description：框架Activity
 *<br>author：caowugao
 *<br>time：2021/1/27 0027 16:57
 */
open abstract class FrameActivity<BINDING : ViewDataBinding, MODEL : BaseVM> : AppCompatActivity(), IBaseView{

    protected lateinit var mBinding :BINDING
    protected lateinit var mModel : MODEL

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val layoutId = getLayoutId()
        if (layoutId != null && layoutId != 0 && layoutId != -1) {
            mBinding = DataBindingUtil.setContentView(this, layoutId)
        } else {
            val layoutView = getLayoutView()
            if (layoutView != null) {
                mBinding = DataBindingUtil.bind<BINDING>(layoutView)!!
            }
        }

        mBinding.lifecycleOwner = this
        val variableId = getVariableId()
        val variableModel = getVariableModel()
        mModel = variableModel
        variableModel.attachUI(this)
        if (variableId != null && variableId != 0 && variableId != -1) {
            mBinding.setVariable(variableId, variableModel)
        }

        initView()
        initData(savedInstanceState)
    }

    protected open fun initData(savedInstanceState: Bundle?) {
        mModel.clickEvent.observe(this) {v ->
            onClick(v)
        }
    }

    protected open fun initView() {

    }

    open fun getVariableModel(): MODEL = ViewModelProvider(this).get(getModelClass(1))

    /**
     * index:表示该泛型参数在类的位置。比如 A<T,E..>.从0开始
     */
    protected fun getModelClass(index : Int) : Class<MODEL> = GsonTypeToken.getSuperclassTypeParameterClass(javaClass, index)!!


    abstract fun getVariableId(): Int?

    open fun getLayoutView(): View? = null

    abstract fun getLayoutId(): Int?

    override fun showLoading() {
    }

    override fun hideLoading() {
    }

    override fun showEmpty() {
    }

    override fun showError() {
    }

    override fun showNetError() {
    }

    override fun onClick(v: View?) {
    }

    override fun onLongClick(v: View?): Boolean {
        return false
    }

    override fun onItemClick(position: Int, bean: Any?) {
    }

    override fun onItemLongClick(position: Int, bean: Any?) {
    }

    override fun getLifecycleOwner(): LifecycleOwner  = this

}